import { fetchWithAuth } from "@/app/cg06/api/common"
import type { ResDataType } from "@/app/cg06/api/common"
import { ListType } from "@/app/shipping/interfaces"
import { ApiFormatData, ApiFreightListFormatData } from "@/app/shipping/mock/all"

function serializeQueryParams(params: { [key: string]: any }): string {
  const str = Object.keys(params)
    .filter((f) => params[f] !== undefined && params[f] !== null)
    .map((key) => {
      if (Array.isArray(params[key])) {
        return params[key].map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&")
      } else {
        return `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
      }
    })
    .join("&")
  if (str) {
    return `?${str}`
  }
  return ""
}

/** 义乌货运指数大屏 */
export const getInfo = async (query: any) => {
  const str = serializeQueryParams(query)
  const { data } = await fetchWithAuth<ResDataType<{ indicatorList: ListType[]; freightList: ListType[] }>>(
    `/big-screen/freightIndicator/getInfo${str}`
  )
  // console.log(data)
  let allEarth: any[] = [];
  // 主数据 各个战区的数据
  const indicatorList = (data?.indicatorList || [])
    .filter((f: any) => f.label)
    .sort((a: any, b: any) => a.sort - b.sort)
    .map((item) => {
      const allData = ApiFormatData(item.data, item.event, item.label)
      if (item.label === '全球') {
        allEarth = allData.average
      }
      if (item.precent) {
        item.precent = item.precent * 100
      }
      if (item.max) {
        item.max = item.max * 100
      }
      if (item.mid) {
        item.mid = item.mid * 100
      }
      if (item.min) {
        item.min = item.min * 100
      }
      return {
        ...item,
        data: allData.values,
        allEarth,
        // date: allData.dates,
        week: allData.week,
        event: allData.eventAry,
        // 预测值
        futureList: allData.futureList
      }
    })
  // 右上角 海运所数据
  const freightList = (data?.freightList || []).map((item) => {
    const values = ApiFreightListFormatData(item.data).values
    if (item.precent) {
      item.precent = item.precent * 100
    }
    return {
      ...item,
      data: values
    }
  })

  return {
    indicatorList,
    freightList
  }
}
